﻿#include "custom_data.h"
#include <iostream>
#include <sstream>

using namespace boost::interprocess;

custom_data::custom_data()
{
}

void custom_data::init(managed_shared_memory &segment)
{
    segement_ = managed_shared_memory(open_or_create, "my_shared_memory", 524288000);
    const shmem_data_map_allocator data_map_allocator(segement_.get_segment_manager());
    data_map_ptr_ = segement_.find_or_construct<shmem_data_map>("data_map_ptr_")(data_map_allocator);
    const shmem_access_time_map_allocator access_time_map_allocator(segement_.get_segment_manager());
    access_time_map_ptr_ = segement_.find_or_construct<shmem_access_time_map>("access_time_map_ptr_")(access_time_map_allocator);
    mutex_ptr_ = segement_.find_or_construct<interprocess_mutex>("mutex_ptr_")();
}

bool custom_data::set(std::string key, std::string value)
{
    scoped_lock<interprocess_mutex> lock(*mutex_ptr_);
    auto it = data_map_ptr_->find(key.c_str());
    if (it != data_map_ptr_->end())
    {
        shmem_string_allocator string_allocator(segement_.get_segment_manager());
        shmem_string str(string_allocator);
        str = value;

        std::cout << "custom_data::set update" << std::endl;
        it->second.data = boost::interprocess::string(value.data(), value.size());
        auto old_access = it->second.access_time;
        it->second.access_time = time(nullptr);
        // 更新访问时间
        // updateAccessTimeMap(key, old_access, it->second.access_time);
    }
    else
    {
        // auto now = (uint64_t)time(nullptr);
        // data_map_ptr_->insert({key.c_str(), {boost::interprocess::string(value.c_str()), now}});
        std::cout << "custom_data::set insert" << std::endl;
        const shmem_string_allocator data_map_allocator(segement_.get_segment_manager());
        data_body body(data_map_allocator);
        body.data = boost::interprocess::string(value.data(), value.size());
        body.access_time = time(nullptr);
        data_map_ptr_->insert(std::make_pair(key.c_str(), body));
        // updateAccessTimeMap(key, now, now);
    }
    // clearCache();
    return true;
}